package com.xishu.upgrade;

import com.xishu.config.Config;
import com.xishu.entity.AbstractEntity;
import com.xishu.entity.shop.CompanyMainItem;
import com.xishu.entity.shop.Item;
import com.xishu.entity.shop.PriceConfig;
import com.xishu.entity.shop.SetMenuOneItem;
import com.xishu.service.CommonService;
import com.xishu.service.ItemService;
import com.xishu.util.DateUtil;
import com.xishu.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class UpgradeItemService implements Tools {
    private static Logger logger = LoggerFactory.getLogger(UpgradeItemService.class);
    private CommonService commonService = CommonService.getInstance();
    ItemService itemService = ItemService.getInstance();
    private static UpgradeItemService instance = new UpgradeItemService();

    private UpgradeItemService() {
    }

    public static UpgradeItemService getInstance() {
        return instance;
    }

    /**
     * 将套餐里面的份数改成最大值，最小值
     *
     * @param item
     */
    public void upgradeSetMenu(Item item) {
        if (!getBoolean(item.getSetMenu())) {
            logger.info("not set menu item");
            return;
        }

        //只有套餐里面设置了份数才处理
        List<SetMenuOneItem> setMenuOneItemList = item.getSetMenuOneItemList();
        if (isEmpty(setMenuOneItemList)) {
            logger.info("set menu one item list is empty");
            return;
        }

        setMenuOneItemList.stream().filter(setMenuOneItem -> setMenuOneItem.getItemNumber() != null && setMenuOneItem.getMaxNumber() == null && setMenuOneItem.getMinNumber() == null)
                .forEach(setMenuOneItem -> {
                    setMenuOneItem.setMinNumber(setMenuOneItem.getItemNumber());
                    setMenuOneItem.setMaxNumber(setMenuOneItem.getItemNumber());
                });

        try {
            commonService.save(item);
        } catch (Exception e) {
            logger.error("e", e);
        }
    }


    public void addUpdateTime() {
        if (Config.getInstance().addItemUpdateTime()) {
            try {
                commonAddUpdateTime(Item.class);
                commonAddUpdateTime(CompanyMainItem.class);
            } catch (Exception e) {
                logger.error("e", e);
            }
        }
    }

    private <T extends AbstractEntity> void commonAddUpdateTime(Class<T> tClass) throws Exception {
        CommonService.getInstance().doAll(tClass.newInstance(), item -> {
            if (item.getUpdateTime() == null) {
                item.setUpdateTime(item.createTime);
                try {
                    CommonService.getInstance().save(item);
                } catch (Exception e) {
                    logger.error("e", e);
                }
            }

            if (item.getUpdateDate() == null) {
                item.setUpdateDate(DateUtil.formatDate(item.updateTime));
                try {
                    CommonService.getInstance().save(item);
                } catch (Exception e) {
                    logger.error("e", e);
                }
            }
        });
    }

    /**
     * 只有有一个场景价格
     */
    public void onlyOneScenePrice() {
        if (!Config.getInstance().onlyOneScenePrice()) {
            logger.info("onlyOneScenePrice upgrade false");
            return;
        }

        CommonService.getInstance().doAll(new Item(), item -> {
            if (!itemService.hasSameScenePrice(item)) {
                return;
            }

            List<PriceConfig> priceConfigList = new ArrayList<>();

            Map<Long, List<PriceConfig>> sceneIdGroup = item.getPriceConfigList().stream().collect(Collectors.groupingBy(p -> p.getSceneId()));

            for (Map.Entry<Long, List<PriceConfig>> entry : sceneIdGroup.entrySet()) {
                List<PriceConfig> configList = entry.getValue();

                if (configList.size() == 1) {
                    priceConfigList.addAll(configList);
                    continue;
                }

                List<PriceConfig> filterPriceConfigList = configList.stream().filter(priceConfig -> getDouble(priceConfig.getPrice()) > 0).collect(Collectors.toList());

                if (filterPriceConfigList.size() > 0) {
                    logger.info("filterPriceConfigList size is {}", filterPriceConfigList.size());
                    priceConfigList.add(filterPriceConfigList.get(0));
                } else {
                    //一个也没有，那么随便添加一个
                    priceConfigList.add(configList.get(0));
                }
            }

            item.setPriceConfigList(priceConfigList);
            try {
                commonService.save(item);
            } catch (Exception e) {
                logger.error("e", e);
            }
        });
    }


    /**
     * 如果是场景菜品，那么
     */
    public void onlyScenePrice() {
        if (!Config.getInstance().onlyScenePrice()) {
            logger.info("onlyScenePrice upgrade false");
            return;
        }

        CommonService.getInstance().doAll(new Item(), item -> {
            if (!itemService.isSceneItem(item)) {
                return;
            }

            try {
                itemService.onlyOnePrice(item);
            } catch (Exception e) {
                logger.error("e", e);
            }
        });
    }


    /**
     * 处理掉菜的场景的shopID跟菜的shopID不一样的菜（以前导入的时候产生的）
     */
    public void addUpgradeItemSceneMapping() {
        if (!Config.getInstance().upgradeItemSceneMapping()) {
            return;
        }

        Item item = new Item();
        item.setSuggestion(true);
        CommonService.getInstance().doAll(item, i -> {
            if (!itemService.isSceneItem(i)) {
                return;
            }

            try {
                itemService.dealItemSceneMapping(i);
            } catch (Exception e) {
                logger.error("e", e);
            }

        });

    }
}
